//
//  JSONCategory.m

#import "JSONCategory.h"

#pragma mark - JSONUtil

@interface JSONUtil : NSObject

@end

@implementation JSONUtil

/**
 *  返回对象的JSON二进制数据
 *  如果对象不合法（不是NSString、NSNumber、NSArray、NSDictionary及NSNull对象），则返回nil
 *
 *  @param object 待JSON化的对象
 *
 *  @return 对象的JSON二进制数据
 */
+ (NSData *)JSONDataWithObject:(id)object
{
    NSData *resultData = nil;
    if ([NSJSONSerialization isValidJSONObject:object]) {
        NSError *error;
        resultData = [NSJSONSerialization dataWithJSONObject:object
                                                     options:NSJSONWritingPrettyPrinted
                                                       error:&error];
    }

    return resultData;
}

/**
 *  返回对象的JSON字符串
 *  如果对象不合法（不是NSString、NSNumber、NSArray、NSDictionary及NSNull对象），则返回nil
 *
 *  @param object 待JSON化的对象
 *
 *  @return 对象的JSON字符串
 */
+ (NSString *)JSONStringWithObject:(id)object
{
    NSString *resultStr = nil;
    NSData *resultData = [JSONUtil JSONDataWithObject:object];
    if (resultData) {
        resultStr = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }

    return resultStr;
}

@end

#pragma mark - NSString+JSON

@implementation NSString (JSON)

- (id)objectFromJSONString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] objectFromJSONData];
}

- (NSData *)JSONData
{
    return [JSONUtil JSONDataWithObject:self];
}

- (NSString *)JSONString
{
    return [JSONUtil JSONStringWithObject:self];
}

@end

#pragma mark - NSData+JSON

@implementation NSData (JSON)

- (id)objectFromJSONData
{
    id object = nil;
    if (self) {
        NSError *error;
        object = [NSJSONSerialization JSONObjectWithData:self options:kNilOptions error:&error];
    }

    return object;
}

@end

#pragma mark - NSArray+JSON

@implementation NSArray (JSON)

- (NSData *)JSONData
{
    return [JSONUtil JSONDataWithObject:self];
}

- (NSString *)JSONString
{
    return [JSONUtil JSONStringWithObject:self];
}

@end

#pragma mark - NSDictionary+JSON

@implementation NSDictionary (JSON)

- (NSData *)JSONData
{
    return [JSONUtil JSONDataWithObject:self];
}

- (NSString *)JSONString
{
    return [JSONUtil JSONStringWithObject:self];
}

@end
